using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class PreloadDataMenu : MonoBehaviour {
	
	public UILabel loadingLabel;
	public UILabel percent;
	public UILabel count;
	public UISlider progressBar;
	
	Dictionary<string, Dictionary<string,string>> data;
	Dictionary<string, Dictionary<string,string>>.Enumerator en;
	Dictionary<string,string>.Enumerator innerEn;
	DirectoryInfo dir;
	
	int total;
	int processed = 0;

	// Use this for initialization
	IEnumerator Start () {
		
		Directory.Delete(Application.persistentDataPath, true);
		
		GameObject JSONDBObj = Resources.Load("JSONDB", typeof(GameObject)) as GameObject;
		
		JSONDB database = JSONDBObj.GetComponent<JSONDB>();
		
		data = database.rules;
		en = data.GetEnumerator();
		en.MoveNext();
		
		foreach(var i in database.rules)
		{
			foreach(var ii in i.Value)
			{
				total++;
			}
		}
		
		yield break;
	}
	
	void Update()
	{
		if(dir == null)
		{
			if(Directory.Exists(Application.persistentDataPath + "/" + en.Current.Key))
				dir = new DirectoryInfo(Application.persistentDataPath + "/" + en.Current.Key);
			else
				dir = Directory.CreateDirectory(Application.persistentDataPath + "/" + en.Current.Key);
			
			innerEn = en.Current.Value.GetEnumerator();
		}
		
		loadingLabel.text = innerEn.Current.Key;
		percent.text = Mathf.Floor(((float)processed/(float)total)*100) + "%";
		count.text = processed + "/" + total;
		progressBar.rawValue = ((float)processed/(float)total);
		
		try
		{
			using(StreamWriter writer = File.CreateText(dir.FullName + "/" + innerEn.Current.Key))
			{
				writer.Write(innerEn.Current.Value);
			}
		}
		catch
		{
			
		}
		
		processed++;
		
		if(!innerEn.MoveNext())
		{
			dir = null;
			if(!en.MoveNext())
			{
				Destroy(gameObject);
				return;
			}
		}
	}
	
}
